import { defineStore } from "pinia";
import AxiosMethods from "@/utils/AxiosMethods";

export const useAuthStore = defineStore('auth', {
  state: () => ({
    id: null,
    name: '',
    password: '',
    role: null,
    phone: ''
  }),
  actions: {
    async login(payload) { // 登录
      try {
        const response = await AxiosMethods.post('users/login', payload);
        if (response.data.code === true) {
          this.$patch((state) => {
            state.id = response.data.id;
            state.name = payload.name;
            state.role = response.data.role; // 存储用户角色信息
          });
          localStorage.setItem('user', JSON.stringify(response.data));
          return response.data;
        } else {
          throw new Error('登录失败，请检查用户名和密码');
        }
      } catch (error) {
        console.log(error);
        throw error;
      }
    },
    async register(payload) { // 注册
      try {
        const response = await AxiosMethods.post('users/register', payload);
        if (response.data.code === true) {
          this.$patch((state) => {
            state.name = payload.name;
            state.password = payload.password;
            state.role = response.data.role; // 存储用户角色信息
          });
          return response.data;
        } else {
          throw new Error('注册失败，请重试');
        }
      } catch (error) {
        throw error;
      }
    }
  }
});
